package com.chester.quickstarter.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author chester7cheng
 */
@Aspect
@Component
public class ControllerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);

    @Pointcut("execution(* com.chester.quickstarter.controller..*(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void controllerMethodPointcut() {
    }

    @Around("controllerMethodPointcut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        logger.info(">>>" + request.getServletPath() + " - " + request.getMethod() + " - " + proceedingJoinPoint.getSignature().getName());
        Map parameterMap = request.getParameterMap();
        if (parameterMap.size() > 0) {
            logger.info("parameterMap: " + JSON.toJSONString(parameterMap));
        }
        Object[] argus = proceedingJoinPoint.getArgs();
        for (Object item : argus) {
            if (item instanceof JSONObject) {
                logger.info("requestBody: " + JSON.toJSONString(item));
            }
        }

        Object object = proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis();
        logger.info("---" + request.getServletPath() + " - cost time: " + (end - start) + "ms");
        return object;
    }
}
